package net.hserver.apm.plugin.track;

import javassist.CtClass;
import javassist.CtMethod;
import cn.hserver.core.interfaces.TrackAdapter;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.server.context.ConstConfig;
import cn.hserver.core.server.context.HServerContextHolder;
import cn.hserver.core.server.context.Webkit;
import cn.hserver.core.server.util.PropUtil;
import net.hserver.apm.common.DataConfig;
import net.hserver.apm.common.entity.LinkInfo;

import java.util.concurrent.atomic.LongAdder;


@Bean
public class ApmTrack implements TrackAdapter {

    private final static LongAdder ADD=new LongAdder();

    private final static Boolean isTrack = PropUtil.getInstance().getBoolean("amp.track");

    @Override
    public void track(Class aClass, CtMethod ctMethod, StackTraceElement[] stackTraceElements, long l, long l1,long pSpanId,long spanId) throws Exception {
        if (isTrack) {
            Webkit webKit = HServerContextHolder.getWebKit();
            if (webKit != null) {
                LinkInfo linkInfo = new LinkInfo();
                linkInfo.setAppName(ConstConfig.APP_NAME);
                linkInfo.setChainId(webKit.httpRequest.getRequestId());
                linkInfo.setMs((int) (l1 - l));
                linkInfo.setClassName(aClass.getName());
                linkInfo.setMethod(ctMethod.getName());
                linkInfo.setReturnType(ctMethod.getReturnType().getName());
                linkInfo.setParameterType(methodPar(ctMethod));
                linkInfo.setTime(System.currentTimeMillis());
                linkInfo.setPSpanId(String.valueOf(pSpanId));
                linkInfo.setSpanId(String.valueOf(spanId));
                linkInfo.setLevel(String.valueOf(ADD.longValue()));
                ADD.increment();
                HServerQueue.sendQueue("APM_SEND", DataConfig.APM_DATA_LINK_INFO, linkInfo);
            }
        }

    }

    public String methodPar(CtMethod ctMethod) {
        try {
            CtClass[] parameterTypes = ctMethod.getParameterTypes();
            if (parameterTypes==null||parameterTypes.length==0){
                return "";
            }
            StringBuilder p= new StringBuilder();
            for (int i = 0; i < parameterTypes.length; i++) {
                p.append(parameterTypes[i].getName());
                if (i<parameterTypes.length-1){
                    p.append(",");
                }
            }
            return p.toString();
        }catch (Exception e){
            return "";
        }
    }
}
